#!/usr/bin/env node

//Routes File

'use strict'

/* MODULE IMPORTS */
const Router = require('koa-router');
const koaBody = require('koa-body')({multipart: true, uploadDir: '.'});
//const jimp = require('jimp')

const apiResult = require('../modules/apiResult');
const userSession = require('../lib/userSessionUnit');
const items = require('../modules/itemsModules');
/* IMPORT CUSTOM MODULES */
const User = require('../modules/user');

const router = new Router();

/**
 * The secure home page.
 *
 * @name Home Page
 * @route {GET} /
 * @authentication This route requires cookie-based authentication.
 */
router.get('/', async ctx => {
	try {
		var user = userSession.getUserSession(ctx);
		await ctx.render('index', { user: user })
	} catch(err) {
		await ctx.render('error', {message: err.message})
	}
});


router.get('/index/getItems', async ctx =>{
	
	let pageIndex = ctx.query.pageIndex || 1;
	let pageSize = ctx.query.pageSize || 10;
	let search = ctx.query.search;
	
	let userId = userSession.getUserId(ctx);
	
	let result = await items.getItemListAsync("", pageIndex, pageSize, search);

	if (!userSession.isLogin(ctx)) {
		result.list = result.list.map(item => {
			return {
				name: item.name,
				thumbnail: item.thumbnail,
			};
		});
	}else{
		result.list = result.list.map(item => {
			return {
				description: item.description,
				id: item.id,
				intime: item.intime,
				name: item.name,
				photo: item.photo,
				thumbnail: item.thumbnail,
				swapItems: item.swapItems
			};
		});
	}

	return ctx.body = new apiResult(true, 'get items success', result);
});


// /**
//  * The secure home page.
//  *
//  * @name Home Page
//  * @route {GET} /
//  * @authentication This route requires cookie-based authentication.
//  */
// router.get('/', async ctx => {
// 	try {
// 		if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
// 		const data = {}
// 		if(ctx.query.msg) data.msg = ctx.query.msg
// 		await ctx.render('index')
// 	} catch(err) {
// 		await ctx.render('error', {message: err.message})
// 	}
// });


module.exports = router;
